package msg;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import page.PageState;
import usr.Usr;

public class DeleteMsg extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		try {
			HttpSession sess = req.getSession();
			Usr usr = (Usr)sess.getAttribute("usr");
			if(usr == null)
			{
				req.setAttribute("error_cause", PageState.LOGIN_NOT_EXIST);
				req.getRequestDispatcher("login.jsp").forward(req, resp);
				return;
			}
			
			int id = Integer.parseInt(req.getParameter("msgid"));
			Msg msg = new Msg(id);			
			msg.update();
			
			if ( msg.getTo_id() != usr.getId() && usr.getCredit() != 0 ) {
				req.getRequestDispatcher("msgs.jsp").forward(req, resp);
			} else {
				msg.deleteMsg();
				req.getRequestDispatcher("msgs.jsp").forward(req, resp);
			}
		}
		
		catch (IOException | ServletException e) {
			try {
				resp.sendRedirect("u.html");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
}
